import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import {staticRoutes} from '@/router/routes'

import {loginApi,logoutApi,getUserInfoApi} from '@/api/cal/login'

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

	state: (): UserInfoState => ({
    token: getToken() as string,
    name: '', //用户名
    avatar: '', //用户头像
    routes: [], //路由权限列表：哪些可以访问
    buttons: [], // 按钮权限列表：决定哪些按钮可以访问
    menuRoutes: []
  }),

	actions: {
    async login (username: string, password: string) {
      const {token} = await loginApi (username,password) 
      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     if (username==='admin' && password==='111111') {
      //       const token = 'token-atguigu'
            setToken(token)
            this.token = token
            // resolve(token)
      //     } else {
      //       reject(new Error('用户名或密码错误!'))
      //       ElMessage.error('用户名或密码错误!')
      //     }
      //   }, 1000)
      // })
    },
    // 登出
    async reset(){
      // 删除服务器的token
      await logoutApi()
      // 删除local中保存的token
      removeToken()
      // 删除pinia中的数据
      this.token=''
      this.name=''
      this.avatar=''
    },

    // 获取用户信息
    async getInfo () {
      const { name, avatar, buttons, routes } = await getUserInfoApi()
      // 用户名和头像在头部显示
      this.name = name
      this.avatar = avatar
      // 用来权限管理
      this.buttons = buttons
      this.routes = routes
      // 左侧菜单要渲染的路由表
      this.menuRoutes = staticRoutes      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     this.name = 'admin'
      //     this.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
      //     this.menuRoutes = staticRoutes
      //     resolve({name: this.name, avatar: this.avatar, token: this.token})
      //   }, 1000)
      // })
    },

    // reset () {
    //   // 删除local中保存的token
    //   removeToken()
    //   // 提交重置用户信息的mutation
    //   this.token = ''
    //   this.name = ''
    //   this.avatar = ''
    // },
	},
});
